﻿using System.Collections.Generic;
using System.Linq;
using Caseify.Utility;

namespace Caseify.Commands;

/// <summary>
/// 蛇形命名法/下划线命名法‌
/// </summary>
[Command(PackageIds.SnakeCase)]
internal sealed class SnakeCase : BaseCommand<SnakeCase>
{
    protected override async Task ExecuteAsync(OleMenuCmdEventArgs eventArgs)
    {
        await Transform.TextConverterAsync(ConvertToCamelCase2);
    }

    private static string ConvertToCamelCase(string selectedText)
    {
        var charInSelectedText = Transform.TextToChars(selectedText);
        var firstChar = charInSelectedText[0];
        var listOfCharInSelectedText = charInSelectedText.ToList();
        listOfCharInSelectedText.Remove(firstChar);
        var camelCasedText = firstChar.ToString().ToLower() + string.Join("", listOfCharInSelectedText.ToArray());
        return camelCasedText;
    }

    private static string ConvertToCamelCase2(string selectedText)
    {
        var charInSelectedText = Transform.TextToChars(selectedText);
        var firstChar = charInSelectedText[0];
        var listOfCharInSelectedText = charInSelectedText.ToList();
        listOfCharInSelectedText.Remove(firstChar);

        var length = listOfCharInSelectedText.Count;
        var underlineStrIndex = new List<int>();

        for (int i = 0; i < length; i++)
        {
            var item = listOfCharInSelectedText[i];
            if (IsFirstUpper(item))
            {
                underlineStrIndex.Add(i);
                listOfCharInSelectedText[i] = item.ToString().ToLower().ToCharArray()[0];
            }
        }

        var underlineIdx = 0;
        foreach (var index in underlineStrIndex)
        {
            listOfCharInSelectedText.Insert(index + underlineIdx, '_');
            underlineIdx += 1;
        }

        var camelCasedText = firstChar.ToString().ToLower() + string.Join("", listOfCharInSelectedText.ToArray());
        return camelCasedText;
    }

    /// <summary>
    /// 判断字符是否为大写字母
    /// </summary>
    /// <param name="c"></param>
    /// <returns></returns>       
    private static bool IsFirstUpper(char c)
    {
        return c >= 'A' && c <= 'Z';
    }
}